package com.chat.http.service;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import com.chat.dao.LeaveMsgDao;
import com.chat.dao.ChatPeopleRelationDao;
import com.chat.entity.TdChatLeaveMsg;
import com.chat.vo.back.PushMoodBodyVo;
import com.chat.vo.back.PushMoodJsonVo;
import com.chat.websocket.online.OnlineManage;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class PushMoodService {
	
	@Autowired
	private ChatPeopleRelationDao peopleRelationDao;
	@Autowired
	private LeaveMsgDao leaveMsgDao;
	
	/**
	 * 推送说说给好友
	 * @param op 
	 * @param userName
	 * @param headimg
	 * @return
	 * @throws IOException 
	 */
	public boolean pushFriends( String userName, String headimg) throws IOException{
		
		String friends = peopleRelationDao.getAllFriendByUserName(userName);
		if (friends==null||friends.equals("")) {
			return false;
		}
		if (!friends.contains(",")) {
			return this.moodPush(friends, userName, headimg);
		}
		String[] friend = friends.split(",");
		for (String username : friend) {
			this.moodPush(username, userName, headimg);
		}
		
		return true;
	}
	/*************************类内方法********************************/
	private boolean moodPush(String friends,String userName,String headimg){
		PushMoodJsonVo msg = new PushMoodJsonVo();
		PushMoodBodyVo body = msg.getBody();
		body.setDate(new Date().toString());
		body.setFromUser(userName);
		body.setMessage(headimg);
		if (OnlineManage.isOnlined(friends)) {
			try {
				msg.MsgSuccess();
				OnlineManage.getOnlineUser(friends).getSession().sendMessage(new TextMessage(new ObjectMapper().writeValueAsString(msg.toMap())));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		TdChatLeaveMsg leaveMsg = new TdChatLeaveMsg();
		leaveMsg.setTousers(friends);
		leaveMsg.setBodytype(1);
		leaveMsg.setCreatetime(new Date().toString());
		leaveMsg.setFromuser(userName);
		leaveMsg.setIspushed(0);
		leaveMsg.setLeavetype(3);
		leaveMsg.setBody(headimg);
		leaveMsgDao.insertOneLeaveMsg(leaveMsg);
		return true;
	} 
}
